// Magic Software, Inc.
// http://www.magic-software.com
// Copyright (c) 2000, All Rights Reserved
//
// Source code from Magic Software is supplied under the terms of a license
// agreement and may not be copied or disclosed except in accordance with the
// terms of that agreement.  The various license agreements may be found at
// the Magic Software web site.  This file is subject to the license
//
// FREE SOURCE CODE
// http://www.magic-software.com/License/free.pdf

#include "MgcIntegrate.h"

//----------------------------------------------------------------------------
template <class Vector>
MgcSingleCurve<Vector>::MgcSingleCurve (MgcReal fTMin, MgcReal fTMax)
    :
    MgcCurve<Vector>(fTMin,fTMax)
{
}
//----------------------------------------------------------------------------
template <class Vector>
MgcSingleCurve<Vector>::~MgcSingleCurve ()
{
}
//---------------------------------------------------------------------------
template <class Vector>
MgcReal MgcSingleCurve<Vector>::GetSpeedWithData (MgcReal fTime,
    void* pvData)
{
    return ((MgcCurve<Vector>*)pvData)->GetSpeed(fTime);
}
//---------------------------------------------------------------------------
template <class Vector>
MgcReal MgcSingleCurve<Vector>::GetLength (MgcReal fT0, MgcReal fT1) const
{
    assert( m_fTMin <= fT0 && fT0 <= m_fTMax );
    assert( m_fTMin <= fT1 && fT1 <= m_fTMax );
    assert( fT0 <= fT1 );

    return MgcIntegrate::RombergIntegral(fT0,fT1,GetSpeedWithData,
        (void*)this);
}
//---------------------------------------------------------------------------
template <class Vector>
MgcReal MgcSingleCurve<Vector>::GetTime (MgcReal fLength, int iIterations,
    MgcReal fTolerance) const
{
    if ( fLength <= 0.0 )
        return m_fTMin;

    if ( fLength >= GetTotalLength() )
        return m_fTMax;

    // initial guess for Newton's method
    MgcReal fRatio = fLength/GetTotalLength();
    MgcReal fOmRatio = 1.0 - fRatio;
    MgcReal fTime = fOmRatio*m_fTMin + fRatio*m_fTMax;

    for (int i = 0; i < iIterations; i++)
    {
        MgcReal fDifference = GetLength(m_fTMin,fTime) - fLength;
        if ( MgcMath::Abs(fDifference) < fTolerance )
            return fTime;

        fTime -= fDifference/MgcCurve<Vector>::GetSpeed(fTime);
    }

    // Newton's method failed.  If this happens, increase iterations or
    // tolerance or integration accuracy.
    return MgcMath::INFINITY;
}
//---------------------------------------------------------------------------
